package scsc.pub.process.dispatch;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import scsc.pub.data.DispatchConsult;
import scsc.pub.db.DBManage;
import scsc.pub.exception.UnifyUserException;
import scsc.pub.tools.StringUtil;

public class TransferAction implements ActionHandler {

	public void execute(ExecutionContext executionContext) throws Exception {
		// TODO Auto-generated method stub
		String transferList = StringUtil.trim((String) executionContext
				.getVariable("transferList"));
		String transfer = StringUtil.trim((String) executionContext
				.getVariable("transfer"));
		String toAll = StringUtil.trim((String) executionContext
				.getVariable("toAll"));
		DBManage dbmanage = new DBManage();
		String hql = "";
		try {
			if (transfer.equals("1")) {
				if (toAll.equals("1")) {
					hql = "select operator.operatorid from scsc.pub.data.Operator as operator where operator.deptcode in (select dept.deptcode from scsc.pub.data.Department as dept where dept.deptcode like '01%' or dept.deptcode='000000001')";
					ArrayList operatorList = (ArrayList) dbmanage.sqlQuery(hql);
					dbmanage.begin();
					for (int i = 0; i < operatorList.size(); i++) {
						DispatchConsult dispatchConsult = new DispatchConsult();
						dispatchConsult.setProcessInstanceId(executionContext
								.getProcessInstance().getId());
						dispatchConsult.setUserId(operatorList.get(i)
								.toString());
						dispatchConsult.setState("0");
						dispatchConsult.setLatestDate(null);
						dispatchConsult.setRemark("");
						dbmanage.sqlSave(dispatchConsult);
					}
					dbmanage.commit();
				} else if (toAll.equals("0")) {
					StringTokenizer st = new StringTokenizer(transferList, ",");
					dbmanage.begin();
					while (st.hasMoreTokens()) {
						DispatchConsult dispatchConsult = new DispatchConsult();
						dispatchConsult.setProcessInstanceId(executionContext
								.getProcessInstance().getId());
						dispatchConsult.setUserId(st.nextToken());
						dispatchConsult.setState("0");
						dispatchConsult.setLatestDate(null);
						dispatchConsult.setRemark("");
						dbmanage.sqlSave(dispatchConsult);
					}
					dbmanage.commit();
				}
			}
			dbmanage.close();
		} catch (UnifyUserException e) {
			dbmanage.rollback();
			dbmanage.close();
		}
	}

}
